package game.module.item.dao;

import game.module.item.beans.GoodsList;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtobufIOUtil;

@Repository
public class GoodsBinaryDao {

	private LinkedBuffer buffer;
	
	@PostConstruct
	public void init() {
		buffer = LinkedBuffer.allocate(65536);
	}

	@Autowired
	private JdbcTemplate jdbcTemplate;

	public void saveGoods(final int roleId, GoodsList goodsList) {

		final InputStream inputStream;
		try {
			byte[] content = ProtobufIOUtil.toByteArray(goodsList, GoodsList.getSchema(), buffer);
			inputStream = new ByteArrayInputStream(content);
		} finally {
			buffer.clear();
		}
		jdbcTemplate.update("update goods set goods_blob = ? where role_id = ?", new PreparedStatementSetter() {
			@Override
			public void setValues(PreparedStatement ps) throws SQLException {
				ps.setBlob(1, inputStream);
				ps.setInt(2, roleId);
			}
		});
	}

	public GoodsList getGoods(int roleId) {
		List<GoodsList> goodList = jdbcTemplate.query("select goods_blob from goods where role_id = ?", new Object[] { roleId }, new RowMapper<GoodsList>() {
			@Override
			public GoodsList mapRow(ResultSet rs, int rowNum) throws SQLException {
				GoodsList gl = new GoodsList();
				InputStream is = rs.getBinaryStream(1);
				try {
					ProtobufIOUtil.mergeFrom(is, gl, GoodsList.getSchema());
				} catch (IOException e) {
					e.printStackTrace();
				}
				return gl;
			}
		});
		return goodList.get(0);
	}

	public int initGoodsRecord(int roleId) {
		return jdbcTemplate.update("insert into goods(role_id) values(?)", roleId);
	}

	public void removeGoodsByRoleId(int roleId) {
		jdbcTemplate.update("delete from goods where role_id = ?", roleId);
	}

}
